import UIKit

class CreateProjectViewController: BaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ChangePage {
    
    var vcCount = 4
    
    var year: Int = -1
    
    func change(toPage idx: Int) {
        
        if let vc = page.viewControllers?[0] {
            
            if let currentIndex = ctls.index(of: vc) {
                
                if currentIndex < idx {
                    
                    page.setViewControllers([ctls[idx]], direction: .forward, animated: true, completion: nil)
                    
                } else {
                    page.setViewControllers([ctls[idx]], direction: .reverse, animated: true, completion: nil)
                }
                
            }
        }
    }
    
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx > 0 {
                
                return ctls[idx - 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx < ctls.count - 1 {
                
                return ctls[idx + 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            
            let vc = pageViewController.viewControllers![0]
            
            if let index = ctls.index(of: vc) {
                
                slide.slide(toPosition: index)
                
            }
            
        }
    }
    
    
    var applyid = ""
    
    var _applyType = ""
    
    var applyType: String {
        set{
            _applyType = newValue
            if self.projType.count == 0 {
                switch newValue {
                case "30":
                    self.projType = "1"
                    break
                case "40":
                    self.projType = "2"
                    break
                default:
                    break
                }
            }
        }
        get{
            return _applyType
        }
    }
    
    var ctls: Array<UIViewController> = []
    
    let page = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
    
    let slide = SlidePageView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 55)))
    
    let approvalBtn = UIButton(type: .system)
    
    var canApproval = false
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        if canApproval == true {
            approvalBtn.setTitle("审批意见", for: .normal)
            
            approvalBtn.setTitleColor(UIColor.white, for: .normal)
            
            approvalBtn.backgroundColor = UIColor.mainColor
            
            approvalBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
            
            approvalBtn.addTarget(self, action: #selector(approvalAction(_:)), for: .touchUpInside)
            
            self.view.addSubview(approvalBtn)
        }
        
        slide.width = self.view.width
        
        for view in page.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
        let baseinfo = PartialTableViewController()
        
        baseinfo.filePath = .Project
        
        let contents = [["项目名称:":""],["项目简介:":""],["业务产品类别:":""],["项目类型:":""],["项目级别:":""],["所属部门:":""],["项目经理:":""],["项目预计收入(元):":""],["项目预计成本:":""],["预计毛利率:":""],["合同签署情况":""],["客户经理:":""],["客户单位:":""],["客户单位项目负责人:":""],["计划开始日期:":""],["计划结束日期:":""],["预计工作量:":""],["预计投放人数:":""],["项目实施地:":""],["事业部协作情况:":""],["项目目标":""],["项目简介":""],["预计项目进度安排:":""],["项目交付验收标准:":""],["备注:":""],["附件:":""]]
        
        baseinfo.source = contents
        
        ctls.append(baseinfo)
        
        let predicate = PredicateTableViewController()
        
        predicate.picker.showtotal = true
        
        predicate.delegate = self
        
        ctls.append(predicate)
        
        if vcCount > 2 {
            if self.applyType == "30" {
                
                slide.configTitles(["基础信息","预算信息","项目成员","审批记录"])
                
                let peopleInfo = PersonInfoViewController()
                
                ctls.append(peopleInfo)
                
                let approvallist = ApprovalRecordListViewController()
                
                ctls.append(approvallist)
                
            } else {
                
                slide.configTitles(["基础信息","预算信息","项目成员","营销合同","采购合同"])
                
                let peopleInfo = PersonInfoViewController()
                
                ctls.append(peopleInfo)
                
                let salesContract = BaseSectionedTableViewController()
                
                ctls.append(salesContract)
                
                let purchaseContract = BaseSectionedTableViewController()
                
                ctls.append(purchaseContract)
                
            }
        } else {
            slide.configTitles(["基础信息","预算信息"])
        }
        
        page.delegate = self
        
        page.dataSource = self
        
        slide.delegate = self
        
        slide.backgroundColor = UIColor.white
        
        self.view.addSubview(slide)
        
        page.view.backgroundColor = UIColor.white
        
        self.view.addSubview(page.view)
        
        for view in page.view.subviews {
            if let scroll = view as? UIScrollView {
                
                scroll.delegate = slide
                
            }
        }
        
        
        page.setViewControllers([ctls[0]], direction: .forward, animated: false, completion: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBtn), name: NSNotification.Name("RefreshDetail"), object: nil)
        
        self.load(with: "detail")
        
    }
    
    @objc func refreshBtn()->Void{
        self.popobjc()
    }
    
    
    
    @objc func approvalAction(_ : UIButton) -> Void {
        
        let approval = ApprovalSuggestionViewController()
        
        approval.applyId = self.applyid
        
        approval.netPath = "projectManage/mobile/sys/approvalprocess/examineApproval"
        
        approval.businessType = self.applyType
        
         self.navigationController?.present(vc: approval)
        
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        if self.canApproval == true {
            approvalBtn.frame = CGRect.init(x: 0, y: self.view.height - 55, width: self.view.width, height: 55)
            page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height - self.approvalBtn.height))
        } else {
            page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height))
        }
        
    }
    
    
    override var names: Array<String> {
        get{
            return ["detail","refresh"]
        }
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func suc(json: JSON)->Void{
            
            print(json)
            
            
            //1常规项目 2研发项目 3 其他项目
            let type = json["data"]["projCategory"].int ?? 1
            
            var contents: Array<Dictionary<String,String?>> = []
            
            let data = json.contents?["data"]?.contents
            
            contents.append(["项目名称:":data?["gsProjName"]?.rawString()])
            
            if type != 3 {
                contents.append(["所属综合计划:":data?["projectname"]?.rawString()])
            }
            
            let status = data?["status"]?.int ?? 0
            switch status {
            case 1:
                contents.append(["项目状态:":"已立项"])
                break
            case 2:
                contents.append(["项目状态:":"已启动"])
                break
            case 3:
                contents.append(["项目状态:":"已结束"])
                break
            case 4:
                contents.append(["项目状态:":"已验收"])
                break
            case 5:
                contents.append(["项目状态:":"已结项"])
                break
            case 6:
                contents.append(["项目状态:":"终止或挂起"])
                break
            default:
                break
            }
            
            contents.append(["项目属性:": json["data"]["projAttributeName"].string])
            //
            
            if self.applyType != "30" {
                contents.append(["项目编号:":data?["projectNumber"]?.rawString()])
            }
            
            
            if type != 3 {
                contents.append(["协同部门": data?["assistDept"]?.rawString()])
                contents.append(["项目简称:":data?["projNameShort"]?.rawString()])
                contents.append(["业务产品类别:":data?["productType"]?.rawString()])
                if let type = data?["projType"]?.rawValue as? Int {
                    switch type {
                    case 1:
                        contents.append(["项目类型:":"合同开发"])
                        break
                    case 2:
                        contents.append(["项目类型:":"自主研发"])
                        break
                    case 3:
                        contents.append(["项目类型:":"生产销售类"])
                        break
                    case 4:
                        contents.append(["项目类型:":"工程类"])
                        break
                    case 5:
                        contents.append(["项目类型:":"运维服务类"])
                        break
                    case 6:
                        contents.append(["项目类型:":"咨询类"])
                        break
                    case 7:
                        contents.append(["项目类型:":"融资性租赁"])
                        break
                    case 8:
                        contents.append(["项目类型:":"经营性租赁"])
                        break
                    case 9:
                        contents.append(["项目类型:":"综合管理类"])
                        break
                    case 10:
                        contents.append(["项目类型:":"其他类"])
                        break
                    case 11:
                        contents.append(["项目类型:":"实施类"])
                        break
                    default:
                        contents.append(["项目类型:":"其他"])
                        break
                    }
                } else  {
                    contents.append(["项目类型:":"其他"])
                }
                
                let projLevel = data?["projLevel"]?.int ?? 0
                
                if projLevel == 1 {
                    contents.append(["项目级别:":"公司"])
                } else if projLevel == 2 {
                    contents.append(["项目级别:":"部门"])
                } else {
                    contents.append(["项目级别:":"未知"])
                }
            }
            
            let predicate = self.ctls[1] as! PredicateTableViewController
            
            predicate.feeList = data?["listDetail"]?.array ?? []
            if self.applyType == "30" {
                predicate.ifwithamount = false
            } else {
                predicate.ifwithamount = true
            }
            if let listBudgetMap = data?["listBudgetMap"]?.array {
                predicate._source = listBudgetMap
                if let years = data?["list"]?.array {
                    predicate.years = years.map({ (str) -> String in
                        return str.rawString() ?? ""
                    })
                    predicate.tableView.reloadData()
                } else {
                    predicate.years = predicate._source.map({ (json) -> String in
                        return json.contents?["year"]?.rawString() ?? ""
                    }).filterDuplicates({$0})
                }
            } else if let listBudget = data?["listBudget"]?.array {
                predicate._source = listBudget
                predicate.years = predicate._source.map({ (json) -> String in
                    return json.contents?["year"]?.rawString() ?? ""
                }).filterDuplicates({$0})
            }
            
            
            predicate.tableView.reloadData()
            
            contents.append(["所属部门:":data?["applyDept"]?.rawString()])
            
            contents.append(["项目经理:":data?["projManagerName"]?.rawString()])
            
            if let predictIncome = data?["projEstimatedRevenue"]?.double {
                
                contents.append(["项目预计收入(元):": String(format: "%.2f", predictIncome / 100).rmbformat])
                
            } else {
                
                contents.append(["项目预计收入(元):":""])
                
            }
            
            if let fee = data?["projBudget"]?.double {
                
                contents.append(["项目预计成本(元):":String(format: "%.2f", fee / 100).rmbformat])
                
            } else {
                
                contents.append(["项目预计成本(元):":""])
                
            }
            
            contents.append(["预计毛利率:":data?["estimatedGrossprofit"]?.rawString()])
            
            if type != 3 {
                 contents.append(["合同签署情况:":data?["constract"]?.rawString()])
            }
            
            
            if self.applyType != "30" {
                contents.append(["立项日期:":data?["setDate"]?.rawString()])
            }

            if type != 3 {
                contents.append(["客户经理:":data?["customerManager"]?.rawString()])
                contents.append(["客户单位:":data?["clientUnit"]?.rawString()])
                contents.append(["客户单位项目负责人:":data?["clientProjManager"]?.rawString()])
            }
            
            contents.append(["计划开始日期:":data?["beginDate"]?.rawString()])
            
            contents.append(["计划结束日期:":data?["endDate"]?.rawString()])
            
            if type != 3 {
                contents.append(["预计工作量:":data?["estimatedWork"]?.rawString()])
                contents.append(["预计投放人数:":data?["estimatedLabor"]?.rawString()])
                contents.append(["项目实施地:":data?["estimatedPlace"]?.rawString()])
                contents.append(["事业部协作情况:":data?["deptCorporation"]?.rawString()])
                contents.append(["项目目标:":data?["projGoal"]?.rawString()])
            }
            
            if self.applyType != "30" {
                if let infos = data?["listProjUser"]?.array {
                    
                    let info = self.ctls[2] as! PersonInfoViewController
                    
                    info.source = infos
                    
                    info.tableView.reloadData()
                }//项目用户
                
                if let projectContractList = data?["projectContractList"]?.array {
                    var contents: [[Dictionary<String,String?>]] = []
                    let sale = self.ctls[3] as! BaseSectionedTableViewController
                    for item in projectContractList {
                        var dics: [Dictionary<String,String?>] = []
                        dics.append(["合同名称:": item.contents?["contractname"]?.rawString()])
                        dics.append(["合同编号:": item.contents?["contractid"]?.rawString()])
                        let signingMoney = item.contents?["signmoney"]?.double ?? 0
                        dics.append(["决算金额(元):": String(format: "%.2f", signingMoney / 100).rmbformat])
                        let invoiceMoney = item.contents?["invoiceMoney"]?.double ?? 0
                        dics.append(["已开票金额(元):": String(format: "%.2f", invoiceMoney / 100).rmbformat])
                        let alreadyPaidMoney = item.contents?["alreadyPaidMoney"]?.double ?? 0
                        dics.append(["已回款金额(元):": String(format: "%.2f", alreadyPaidMoney / 100).rmbformat])
                        let notback = invoiceMoney - alreadyPaidMoney
                        dics.append(["开票未回款金额(元):": String(format: "%.2f", notback / 100).rmbformat])
                        contents.append(dics)
                    }
                    sale.source = contents
                    sale.tableView.reloadData()
                }//x营销
                
                if let list = data?["purchaseContracts"]?.array {
                    var contents: [[Dictionary<String,String?>]] = []
                    let sale = self.ctls[4] as! BaseSectionedTableViewController
                    for item in list {
                        var dics: [Dictionary<String,String?>] = []
                        dics.append(["合同名称:": item.contents?["contractName"]?.rawString()])
                        dics.append(["合同编号:": item.contents?["contractNum"]?.rawString()])
                        let signingMoney = item.contents?["finalAmount"]?.double ?? 0
                        dics.append(["决算金额(元):": String(format: "%.2f", signingMoney / 100).rmbformat])
                        let invoiceMoney = item.contents?["invoiceMoney"]?.double ?? 0
                        dics.append(["已来票金额(元):": String(format: "%.2f", invoiceMoney / 100).rmbformat])
                        let alreadyPaidMoney = item.contents?["paymentMoney"]?.double ?? 0
                        dics.append(["已付款金额(元):": String(format: "%.2f", alreadyPaidMoney / 100).rmbformat])
                        contents.append(dics)
                    }
                    sale.source = contents
                    sale.tableView.reloadData()
                }//采购合同
            } else {
                
                if let infos = data?["listProjUser"]?.array {
                    
                    let info = self.ctls[2] as! PersonInfoViewController
                    
                    info.source = infos
                    
                    info.tableView.reloadData()
                }//项目用户
                
                if let approvalProcessList = data?["approvalProcessList"]?.array {
                    let approval = self.ctls[3] as! ApprovalRecordListViewController
                    approval.source = approvalProcessList
                    approval.tableView.reloadData()
                }
            }
            
            contents.append(["项目简介:":data?["projContent"]?.rawString()])
            
            if type != 3 {
                contents.append(["预计项目进度安排:":data?["estimatedSchedule"]?.rawString()])
                
                contents.append(["预计交付验收标准:":data?["projAcceptanceStandard"]?.rawString()])
                
                contents.append(["其他说明:":data?["remark"]?.rawString()])
            }
            
            let info = self.ctls[0] as! PartialTableViewController
            
            if let documents = data?["attachFiles"]?.array {
                info.documents = documents
            }
            
            info.source = contents
            
            info.tableView.reloadData()
        
            var budgetscontents: Array<Dictionary<String,String?>> = []
            
            if let budgets = data?["projectBudget"]?.contents {
                
                year = Int((budgets["year"]?.rawString() ?? "-1"))!
                
                budgetscontents.append(["年份":budgets["year"]?.rawString()])
                
                budgetscontents.append(["预计合同签订金额(元)":String(format: "%.2f",  (budgets["projEstimatedRevenue"]?.double ?? 0) / 100).rmbformat])
                
                budgetscontents.append(["预计合同收入(元)":String(format: "%.2f",(budgets["contractPredict"]?.double ?? 0) / 100).rmbformat])
                
                budgetscontents.append(["预计本年开票金额(元)":String(format: "%.2f", (budgets["invoicePredict"]?.double ?? 0) / 100).rmbformat])
                
                budgetscontents.append(["成本合计(元)":String(format: "%.2f", (budgets["projEstimatedCost"]?.int ?? 0) / 100).rmbformat])
                budgetscontents.append(["人工成本(元)":String(format: "%.2f", (budgets["laborCost"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["人员外包(元)":String(format: "%.2f", (budgets["staffoutCostLabor"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["劳务外包(元)":String(format: "%.2f", (budgets["outsourcingCostLabor"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["服务(元)":String(format: "%.2f", (budgets["outsourcingCostBusiness"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["工程(元)":String(format: "%.2f", (budgets["engineerSubCost"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["物资(元)":String(format: "%.2f", (budgets["materialExpense"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["差旅(元)":String(format: "%.2f", (budgets["travelExpense"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["商务费(元)":String(format: "%.2f", (budgets["businessExpense"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["租赁费(元)":String(format: "%.2f", (budgets["rent"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["低值易耗品(元)":String(format: "%.2f", (budgets["suppliesExpense"]?.double ?? 0) / 100).rmbformat])
                budgetscontents.append(["其他(元)":String(format: "%.2f", (budgets["otherCost"]?.int ?? 0) / 100).rmbformat])
            }
            
        }
        
        func refresh(json: JSON)->Void{
            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
                return
            }
            
            if canoperate == true {
                approvalBtn.isEnabled = true
            } else {
                approvalBtn.isEnabled = false
            }
        }
        
        return name == "detail" ? suc : refresh
        
    }
    
    private var _projType = ""
    var projType: String {
        get{
            return _projType
        }
        set{
            _projType = newValue
            if self.applyType.count == 0 {
                switch newValue {
                case "1":
                    self.applyType = "30"
                    break
                case "2":
                    self.applyType = "40"
                    break
                default:
                    break
                }
            }
        }
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        if year == -1 {
            return ["id":self.applyid,"projectType":self.projType,"businessType": self.applyType]
        } else if year > 0 {
            return ["id":self.applyid,"projectType":self.projType,"businessType": self.applyType,"year": String(year)]
        }
        return ["id":self.applyid,"businessType":self.applyType]
    }
    
    override func path(for name: String) -> String{
        return "projectManage/mobile/sys/projectarchives/view"
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
}


